package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuBoundTo;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService descService;

    @Autowired
    SpuImagesService imagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 该方法涉及多张表的保存，所以要加上@Transactional注解
     * //TODO 处理失败的逻辑高级篇再来处理 如处理失败该怎么回滚，服务不稳定时该怎么处理
     * @param spuSaveVo
     */
    @Transactional
    @Override
    public void saveSupInfo(SpuSaveVo spuSaveVo) {
        //1、保存Spu基本信息   pms_spu_info
        SpuInfoEntity spuInfoEntity=new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSupInfo(spuInfoEntity);
        //2、Spu的描述图片 pms_spu_info_desc   描述图片路径拼接后可能会很长，所以单独使用pms_spu_info_desc表来保存
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity descEntity=new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        //将描述图片信息按，分隔符进行拼接保存
        descEntity.setDecript(String.join(",",decript));
        //保存其他表的数据时，一般注入其他表的service，而不是dao,之后在其他表的service进行相关的业务处理
        descService.saveSpuInofDesc(descEntity);
        //3、Spu保存图片集 pms_spu_images
        List<String> images = spuSaveVo.getImages();
        imagesService.saveImages(spuInfoEntity.getId(),images);
        //4、保存Spu的规格参数  pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        if(baseAttrs != null && baseAttrs.size() > 0){
            List<ProductAttrValueEntity> productAttrValueEntityList=baseAttrs.stream().map(baseAttr -> {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setAttrId(baseAttr.getAttrId());
                productAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
                AttrEntity attrEntity = attrService.getById(baseAttr.getAttrId());
                productAttrValueEntity.setAttrName(attrEntity.getAttrName());
                productAttrValueEntity.setQuickShow(baseAttr.getShowDesc());
                productAttrValueEntity.setSpuId(spuInfoEntity.getId());
                return productAttrValueEntity;
            }).collect(Collectors.toList());
            productAttrValueService.saveProductAttr(productAttrValueEntityList);
        }
        //5、保存Spu的积分信息  gulimall_sms -> sms_spu_bounds   跨数据库操作
        Bounds bounds = spuSaveVo.getBounds();
        SkuBoundTo spuBoundTo=new SkuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        //记录远程调用失败信息
        if(r.getCode() != 0){  //Integer比较时会拆箱成数字
            log.error("远程保存spu积分信息失败");
        }
        //6、保存当前Spu对应的所有Sku信息
        List<Skus> skus = spuSaveVo.getSkus();
        if(skus != null && skus.size()>0){
            skus.forEach(item -> {
                List<Images> imagesList = item.getImages();
                //获取默认图片的url
                String defaultImg="";
                for (Images img : imagesList) {
                    if(img.getDefaultImg() == 1){
                        defaultImg=img.getImgUrl();
                    }
                }
                //6.1）、sku的基本信息； pms_sku_info
                SkuInfoEntity skuInfoEntity=new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                //设置默认图片url
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                //保存sku基本信息
                skuInfoService.saveSkuInfo(skuInfoEntity);
                //保存之后会自动生成skuInfoEntity的自增主键
                Long skuId = skuInfoEntity.getSkuId();
                //6.2）、保存sku的图片信息； pms_sku_images
                List<SkuImagesEntity> skuImagesEntityList = item.getImages().stream().map(image -> {
                    SkuImagesEntity imagesEntity = new SkuImagesEntity();
                    imagesEntity.setSkuId(skuId);
                    //设置是否为默认图片
                    imagesEntity.setDefaultImg(image.getDefaultImg());
                    imagesEntity.setImgUrl(image.getImgUrl());
                    return imagesEntity;
                }).filter(entity -> {  //过滤掉没有图片路径的imagesEntity
                    //返回true则收集，返回false则不收集，filter会比map后执行
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                //批量保存sku的图片集
                skuImagesService.saveBatch(skuImagesEntityList);
                //6.3）、sku的销售属性信息：pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                if(attrs !=null && attrs.size()>0){
                    List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                        SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                        skuSaleAttrValueEntity.setSkuId(skuId);
                        return skuSaleAttrValueEntity;
                    }).collect(Collectors.toList());
                    skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                }
                //6.4）、sku的优惠、满减等信息； gulimall_sms-> sms_sku_ladder\sms_sku_full_reduction\sms_member_price  跨数据库操作
                SkuReductionTo skuReductionTo=new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                //如果满几件打几折或者满减优惠有值，我们才进行远程调用，BigDecimal类型的比较要使用compareTo方法
                if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    //记录远程调用失败信息
                    if(r1.getCode() != 0){
                        log.error("远程保存sku积分信息失败");
                    }
                }
            });
        }

    }

    @Override
    public void saveBaseSupInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    /**
     * 根据条件查询spu列表
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper=new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
           wrapper.and(w -> {
               w.eq("id",key).or().like("spu_name",key);
           });
        }
        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }
        /**
         *    key: '华为',//检索关键字
             catelogId: 6,//三级分类id
             brandId: 1,//品牌id
             status: 0,//商品状态
         */
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    /**
     * 商品上架
     *  1、修改商品的状态
     *  2、发送要保存的商品数据给ES服务进行存储
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
        //1、根据spuid查询关联的所有sku信息
        List<SkuInfoEntity> skus=skuInfoService.getSkusBySpuId(spuId);
        //快速获取所有SkuId，SkuInfoEntity::getSkuId相当于获取每个SkuInfoEntity的skuId并返回
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //TODO 4、查询当前Sku所有能够被检索的规格属性，那些不需要被检索的数据就无需保存，只需查询一遍
        //查询SkuId对应的商品规格
        List<ProductAttrValueEntity> attrValueEntities = productAttrValueService.baseAttrListforspu(spuId);
        //收集所有的商品属性id
        List<Long> attrIds = attrValueEntities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //查询出所有与spu关联的检索属性id
        List<Long> searchAttrs=attrService.selectSearchAttrIds(attrIds);
        //将List转成Set集合
        Set<Long> searchAttrsSet=new HashSet<>(searchAttrs);
        //过滤掉不能被检索的商品规格，并把它封装到SkuEsModel.Attrs中
        List<SkuEsModel.Attrs> attrsList = attrValueEntities.stream().filter(item -> {
            return searchAttrsSet.contains(item.getAttrId());
        }).map(search -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(search, attrs);
            return attrs;
        }).collect(Collectors.toList());
        //TODO 1、远程调用库存服务获取是否有库存，远程调用可以会失败，需要try catch
        Map<Long, Boolean> stockMap=null;
        try {
            R skusHasStock = wareFeignService.getSkusHasStock(skuIds);
            //阿里巴巴通过的TypeReference类
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            //把结果转成Map集合
            stockMap = skusHasStock.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        }catch (Exception e){
            //记录日志
            log.error("库存服务查询异常: {}",e);
        }
        //2、封装每个sku信息
        Map<Long, Boolean> finalStockMap = stockMap;
        //所有要上架的商品
        List<SkuEsModel> products = skus.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);
            //2.1 设置skuPrice skuImg
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            //2.2 设置库存信息
            if(finalStockMap == null){
                //如果远程调用失败，那么默认设置有库存
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }
            //TODO 2.3、热度评分，暂时使用0，后期可以自己扩展逻辑
            skuEsModel.setHotScore(0L);
            //2.4、设置品牌信息和设置分类信息
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            //2.5、设置检索属性
            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).collect(Collectors.toList());
        //TODO 5、将数据发送给检索服务进行保存
        R r = searchFeignService.productStatusUp(products);
        if(r.getCode() == 0){
            //远程调用成功
            //修改当前Spu的发布状态和更新时间
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            //远程调用失败
            //TODO 重复调用? 接口幂等性;重试机制？
        }

    }

    /**
     * 根据skuId获取spu信息
     * @param skuId
     * @return
     */
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        //根据skuId获取Sku信息，进而获取spuID
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        Long spuId = skuInfoEntity.getSpuId();
        SpuInfoEntity spuInfoEntity = this.getById(spuId);
        return spuInfoEntity;
    }

}